package yns.springboot.common.sample.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import yns.springboot.common.sample.dto.UserDto;
import yns.springboot.common.sample.service.UserService;
import yns.springboot.common.sample.utility.time.TimeUtility;


@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserService userService;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@GetMapping("/getUser")
	public String getUser() {
		logger.info("getUser");

		List<UserDto> list =  userService.getUser();
		String result = JSON.toJSON(list).toString();

		return result;
	}

	@PostMapping("/addUser")
	public String addUser() {
		logger.info("addUser");

		UserDto userDto = new UserDto();
		userDto.setUserName("Test" + TimeUtility.getCurrentTime());
		userDto.setUserPwd(passwordEncoder.encode("123456"));
		userDto.setRoleID(1);
		
		int returnCode = userService.addUser(userDto);
		
		JSONObject result = new JSONObject();
		result.put("result", returnCode);
		
		logger.info("addUser : " + result);
		
		return result.toJSONString();
	}

	@GetMapping("/getUserByName")
	public String addDataInfo(@RequestParam(value="userName") String userName) {
		logger.info("getUserByName");
		logger.info("getUserByName : " + userName);
		
		UserDto userDto = userService.getUserByName(userName);
		
		String result = JSON.toJSONString(userDto);
		logger.info("getUserByName : " + result);
		
		return result;
	}

	@PutMapping("/updateUser")
	public String updateDataInfo(@RequestBody String jsonData) {
		logger.info("updateUser");
		
		UserDto userDto = new UserDto();
		userDto.setId(2);
		userDto.setActive(2);
		
		int result = userService.updateUser(userDto);
		
		JSONObject resultJsonObject = new JSONObject();
		resultJsonObject.put("result", result);
		
		logger.info("updateDataInfo : " + resultJsonObject.toJSONString());

		return resultJsonObject.toJSONString();
	}
	
	


}
